const types = require('../action-types.js');
const {request} = require('utils/request');

function queryAppConfigs() {
  return async (dispatch) => {
    const res = await request({
      url: 'api/source/list/app_configs',
      method: 'post',
      data: {
        columns: ['id', 'appName'],
        pageSize: 100
      }
    });
    if (res.code === '0') {
      dispatch({
        type: types.SET_APP_CONFIGS,
        configs: res.data.list
      });
    }
    return res;
  };
}

function queryById(id) {
  return async (dispatch) => {
    const res = await request({
      url: `api/source/queryById/app_configs/${id}`,
      method: 'post'
    });
    if (res.code === '0') {
      dispatch({
        type: types.SET_CURRENT_CONFIG,
        config: res.data
      });
    }
    return res;
  };
}

function addConfig(appName, configs) {
  return async (dispatch) => {
    const res = await request({
      url: 'api/source/add/app_configs',
      method: 'post',
      data: {
        data: {
          appName,
          configs
        }
      }
    });
    return res;
  };
}

function editConfig(id, configs, appName) {
  return async (dispatch) => {
    const res = await request({
      url: `api/source/updateById/app_configs/${id}`,
      data: {
        data: {
          configs,
          appName
        }
      },
      method: 'post'
    });
    return res;
  };
}

// 根据id删除
function deleteById(id) {
  return async (dispatch) => {
    const res = await request({
      url: `api/source/deleteById/app_configs/${id}`,
      method: 'post'
    });
    return res;
  };
}

module.exports = {
  queryAppConfigs,
  queryById,
  addConfig,
  editConfig,
  deleteById
};
